package com.javalong.affairs.common;

import java.util.HashMap;

public class ServiceLocator {

	private static ServiceLocator serviceLocator = null;

	private HashMap<String, Object> mapObj;

	// private
	public synchronized static ServiceLocator GetInstance() {
		if (serviceLocator == null) {
			serviceLocator = new ServiceLocator();
			serviceLocator.init();
		}
		return serviceLocator;
	}

	private void init() {
		mapObj = new HashMap<String, Object>();
	}

	@SuppressWarnings("unchecked")
	public <T> T getInstance(Class<T> c) {
		String name = c.getName();
		T obj = null;
		if (mapObj.containsKey(name)) {
			obj = (T) mapObj.get(name);
		} else {
		}
		return obj;
	}

	public <T> T getInstance(String name, Class<T> c) {
		T obj = null;
		if (mapObj.containsKey(name)) {
			obj = (T) mapObj.get(name);
		} else {
		}
		return obj;
	}

	public <T> void teardown(Class<T> c) {
		String name = c.getName();
		if (mapObj.containsKey(name)) {
			mapObj.remove(name);
		}
	}

	public void register(Object obj) {
		if (obj != null) {
			String name = obj.getClass().getName();
			mapObj.put(name, obj);
		}
	}

	public void register(String name, Object obj) {
		if (mapObj.containsKey(name)) {
		} else {
			try {
				mapObj.put(name, obj);
			} catch (Exception e) {

			}
		}
	}

	public <T> void teardown(String name) {
		if (mapObj.containsKey(name)) {
			mapObj.remove(name);
		}
	}

	public void clear() {
		mapObj.clear();
	}
}
